package com.wenx.ftpcamel;

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class SFtpUtil {
    static Session session = null;

    public static void main(String[] args) {
        String url = "10.10.5.213";
        int port = 21;
        String username = "camel";
        String password = "camel";
        boolean flag = sshSftp(url,port,username,password);
        if(flag){
            List<String> names = getSftpDir("/");
            System.out.println("names = " + names);
        }
        closeSftp();
    }

    /**
     * 连接sftp
     * @param ip
     * @param port
     * @param username
     * @param pwd
     * @return
     */
    public static boolean sshSftp(String ip,int port,String username,String pwd){
        boolean flag = false;
        JSch jsch = new JSch();
        // 采用指定的端口连接服务器
        try {
            session = jsch.getSession(username, ip, port);
            session.setPassword(pwd);
            // 设置第一次登陆的时候提示，可选值：(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
            // 设置登陆超时时间
            session.connect(30000);
            flag = true;
        } catch (JSchException e) {
            e.printStackTrace();
        }
        // 如果服务器连接不上，则抛出异常
        if (session == null) {
            System.out.println("连接不上");
        }
        return flag;
    }

    /**
     * 获取sftp服务器目录
     * @return
     */
    public static List<String> getSftpDir(String path){
        if(path == null || path.equals("")){
            path = "/";
        }
        List<String> dirNames = new ArrayList<String>();
        Channel channel = null;
        try {
            channel = (Channel)session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls(path);
            Iterator iterator = vector.iterator();
            while(iterator.hasNext()){
                //System.out.println(iterator.next());
                String dir = iterator.next().toString();
                String isDir = dir.substring(0,1);
                if(isDir.equals("d")){
                    String[] names = dir.split(" ");
                    String name = names[names.length-1];
                    if(!name.substring(0,1).equals(".")){
                        System.out.println("name = " + name);
                        dirNames.add(name);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("获取目录失败!");
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            if(channel != null){
                channel.disconnect();
            }
        }
        return dirNames;
    }

    /**
     * 关闭
     */
    public static void closeSftp(){
        session.disconnect();
    }
}
